package cn.jilian.meta.handler.generators;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import cn.jilian.entity.MField;
import cn.jilian.entity.Meta;
import cn.jilian.meta.handler.CompGenerator;
import cn.jilian.meta.handler.GeneratorManager;
import cn.jilian.meta.handler.domain.AbstractStore;
import cn.jilian.meta.handler.domain.CellEditorGrid;
import cn.jilian.meta.handler.domain.Column;
import cn.jilian.meta.handler.domain.FormItem;
import cn.jilian.meta.handler.domain.SimpleRestJsonStore;

public class SimpleEditorGridGenerator implements CompGenerator<CellEditorGrid> {

	private GeneratorManager manager;
	
	public SimpleEditorGridGenerator(GeneratorManager manager) {
		this.manager=manager;
	}
	@Override
	public CellEditorGrid convert(Meta meta, Map<String, Object> extConfig) {
		CellEditorGrid  grid=new CellEditorGrid();
		
		grid.setXtype("Ext.view."+meta.getCode());
		grid.setExtend("Ext.grid.Panel");
		grid.setName(meta.getCode());
		grid.setScrollable(Boolean.TRUE);
		grid.setSplit(Boolean.TRUE);
		if(extConfig!=null) {
			grid.setRegion((String) extConfig.get("region"));
		}
		Collection<Column> columns=new ArrayList<>();
		if(extConfig!=null) {
			if(extConfig.containsKey("showColumns")) {
				String showColumns=(String) extConfig.get("showColumns");
				String[] showColumnsArray=StringUtils.split(showColumns,",");
				for(MField f:meta.getFields()) {
					Column c=new Column();
					c.setText(f.getText());
					c.setDataIndex(f.getName());
					columns.add(c);
					Boolean flag=true;
					for(String col:showColumnsArray) {
						if(StringUtils.equalsIgnoreCase(c.getDataIndex(), col)) {
							flag=false;
						}
					}
					if(flag) {
						c.setHidden(true);
					}
				}
			}
		}else {
			for(MField f:meta.getFields()) {
				Column c=new Column();
				c.setText(f.getText());
				c.setDataIndex(f.getName());
				if(f.containsAttr(MField.ENUMS)) {
					String enumCode=(String) f.getAttr(MField.ENUMS);
					enumCode=StringUtils.substringAfterLast(enumCode, "$");
					Map<String,Object> editor=new HashMap<>();
					editor.put("xtype", FormItem.COMBO);
					editor.put("store", enumCode);
					editor.put("valueField", f.getAttr(MField.VALUEFIELD, "CODE"));
					editor.put("displayField", f.getAttr(MField.DISPLAYFIELD, "TEXT"));
					
					c.setEditor(editor);
				}else {
					c.setEditor(FormItem.TEXTFIELD);
				}
				
				columns.add(c);
			}
		}
		CompGenerator<AbstractStore> storeGenerator=manager.getGenerator(SimpleRestJsonStore.class);
		AbstractStore store=storeGenerator.convert(meta, null);
		grid.setTitle(meta.getText()+"列表");
		grid.setStore(store);
		grid.setColumns(columns);
		return grid;
	}

}
